<?php

namespace common\model;

use think\model\RelationModel;

class DataSourceModel extends RelationModel
{
    const IS_DEFAULT_YES = 1; // 是否为默认值-是
    protected static $dataSourceAssocMap = [];
    //自动验证
    protected $_validate = [
        ['key', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['key', '', '', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT],//必须字段
        ['key', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['code', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['code', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['pid', '', '', self::EXISTS_VALIDATE, 'integer', self::MODEL_BOTH],//必须字段
    ];

    // 自动完成
    protected $_auto = [
        ['created', 'time', self::MODEL_INSERT, 'function'],
    ];


    /**
     * 获取器：创建时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getCreatedAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * 数据源通过code获取
     * 单次http请求 内存缓存
     * @param $code
     * @return mixed
     */
    public static function getDataSourceByCodeAssoc($code)
    {
        if (!isset(self::$dataSourceAssocMap[$code])) {
            $data = model(self::class)->where([
                'code' => $code
            ])
                ->field("key,value")
                ->select();
            self::$dataSourceAssocMap[$code] = array_column($data, 'value', 'key');
        }

        return self::$dataSourceAssocMap[$code];
    }
}
